import cookie from 'js-cookie'
import Vue from 'vue'
const http = {
    install(Vue, options) {
        Vue.prototype.$post = function(url, data = {}) {
            return new Promise((resolve, reject) => {
                url = `http://127.0.0.1:3000/api${url}`;
                const xhr = new XMLHttpRequest();
                xhr.open("POST", url);
                xhr.setRequestHeader('Content-type', 'application/json');
                let ya = cookie.get('__ya');
                if (ya) xhr.setRequestHeader('__ya', ya);
                let domain = cookie.get('__domain');
                if (!domain) {
                    window.vueRoot.$notification.error({
                        message: "错误",
                        description: '无法获取您的domain信息，请联系管理员'
                    });
                    window.location.href = '/login'
                }
                xhr.setRequestHeader('__domain', domain);
                xhr.onload = _ => {
                    let result = JSON.parse(xhr.responseText);
                    if (result.error) {
                        window.vueRoot.$notification.error({
                            message: "错误",
                            description: result.detail
                        });
                        //todo:
                        if (result.detail == 'need login') {
                            window.location.href = '/login'
                        }
                    }
                    resolve(result);
                }
                xhr.onerror = _ => reject(xhr.statusText);
                xhr.send(JSON.stringify(data));
            });
        }
        Vue.prototype.$emptyId = "00000000-0000-0000-0000-000000000000"
    }
}
Vue.use(http);
export default http;